﻿using System;
using System.Collections;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using System.Net;

namespace Kwan.Helper.Strings
{
    public class FileHelper
    {
        #region 续写文件
        /// <summary>
        /// 续写文件
        /// </summary>
        /// <param name="str">需写入的字符串</param>
        /// <param name="fileName">文件名称</param>
        /// <returns>提示信息</returns>
        public static string WriteDataFile(string str, string fileName)
        {
            string result = "写入成功!";
            if (String.IsNullOrEmpty(str)) { return "文件名称不能为空!"; }
            string solutionPath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            if (solutionPath[solutionPath.Length - 1] != '\\') solutionPath = solutionPath + "\\";
            string filePath = solutionPath + fileName;
            Encoding code = Encoding.GetEncoding("utf-8");
            //如果文件不存在,将创建文件
            if (!File.Exists(filePath))
            {
                File.Create(filePath);
            }

            StreamReader sr = null;
            StreamWriter sw = null;
            string strOld = "";
            try
            {
                sr = new StreamReader(filePath, code);
                strOld = sr.ReadToEnd(); // 读取文件
                sr.Close();
            }
            catch (Exception exp)
            {
                result = exp.Message;
            }

            // 写文件 
            try
            {
                sw = new StreamWriter(filePath, false, code);
                sw.Write(strOld + str);
                sw.Flush();
                sw.Close();
            }
            catch (Exception exp)
            {
                result = exp.Message;
            }
            return result;
        }
        #endregion

        #region 创建文件夹
        /// <summary>
        /// 创建文件夹
        /// </summary>
        /// <param name="Folder">文件夹名称</param>
        /// <returns>提示信息</returns>
        public static void CreateFolder(string Folder)
        {
            string solutionPath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            if (solutionPath[solutionPath.Length - 1] != '\\') solutionPath = solutionPath + "\\";
            string path = solutionPath + Folder;
            Encoding code = Encoding.GetEncoding("utf-8");
            //如果文件不存在,将创建文件
            if (!Directory.Exists(path))
            {
                // Create the directory it does not exist.
                Directory.CreateDirectory(path);
            }
        }
        #endregion

        #region 获取Html
        /// <summary>
        /// 创建Cookie
        /// </summary>
        /// <param name="strHtml">待转化的字符串</param>
        /// <returns>经过转化的字符串</returns>
        public static string PostAndGetHTML(string targetURL, CookieContainer cc, byte[] data)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(targetURL);
            request.Method = "POST";    //post
            request.ContentType = "x-www-form-urlencoded";
            request.ContentLength = data.Length;
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727)";
            request.CookieContainer = cc;
            //request.KeepAlive = false;

            Stream newStream1 = request.GetRequestStream();
            newStream1.Write(data, 0, data.Length);
            newStream1.Close();
            //request.CookieContainer = cc;
            HttpWebResponse response1 = (HttpWebResponse)request.GetResponse();
            //cc.Add(response1.Cookies);
            Stream stream1 = response1.GetResponseStream();
            string result = new StreamReader(stream1, System.Text.Encoding.UTF8).ReadToEnd();
            return result;
        }
        #endregion

        #region 获取Session
        /// <summary>
        /// 创建Cookie
        /// </summary>
        /// <param name="strHtml">待转化的字符串</param>
        /// <returns>经过转化的字符串</returns>
        public static string PostAndGetSession(string targetURL, CookieContainer cc, Hashtable param)
        {
            //prepare the submit data
            string formData = "";
            foreach (DictionaryEntry de in param)
            {
                formData += de.Key.ToString() + "=" + de.Value.ToString() + "&";
            }
            if (formData.Length > 0)
                formData = formData.Substring(0, formData.Length - 1); //remove last '&'
            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] data = encoding.GetBytes(formData);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(targetURL);
            request.Method = "POST";    //post
            request.ContentType = "x-www-form-urlencoded";
            request.ContentLength = data.Length;
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727)";
            request.CookieContainer = cc;
            request.Credentials = CredentialCache.DefaultCredentials;
            //request.KeepAlive = false;

            Stream newStream1 = request.GetRequestStream();
            newStream1.Write(data, 0, data.Length);
            newStream1.Close();
            //request.CookieContainer = cc;
            HttpWebResponse response1 = (HttpWebResponse)request.GetResponse();
            string sessionid = response1.Headers.Get("Set-Cookie");
            if (!string.IsNullOrEmpty(sessionid))
            {
                sessionid = Format.CutString(sessionid, "ASP.NET_SessionId=", ";")[0];
            }
            return sessionid;
        }
        #endregion

        #region 获取文件字符串
        /// <summary>
        /// 获取文件字符串
        /// </summary>
        /// <param name="fileName">文件名称</param>
        /// <returns>提示信息</returns>
        public static string GetFileString(string fileName)
        {
            string solutionPath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            if (solutionPath[solutionPath.Length - 1] != '\\') solutionPath = solutionPath + "\\";
            string filePath = solutionPath + fileName;
            Encoding code = Encoding.GetEncoding("utf-8");
            //如果文件不存在,将创建文件
            if (!File.Exists(filePath))
            {
                File.Create(filePath);
            }

            StreamReader sr = null;
            string strOld = "";
            try
            {
                sr = new StreamReader(filePath, code);
                strOld = sr.ReadToEnd(); // 读取文件
                sr.Close();
                return strOld;
            }
            catch
            {
                //return exp.Message;
            }
            return "";
        }
        #endregion

        #region 写入文件
        /// <summary>
        /// 写入文件
        /// </summary>
        /// <param name="str">需写入的字符串</param>
        /// <param name="fileName">文件名称</param>
        /// <returns>提示信息</returns>
        public static bool WriteFileString(string str, string fileName)
        {
            string solutionPath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            if (solutionPath[solutionPath.Length - 1] != '\\') solutionPath = solutionPath + "\\";
            string filePath = solutionPath + fileName;
            Encoding code = Encoding.GetEncoding("utf-8");
            //如果文件不存在,将创建文件
            if (!File.Exists(filePath))
            {
                File.Create(filePath);
            }
            StreamWriter sw = null;
            // 写文件 
            try
            {
                sw = new StreamWriter(filePath, false, code);
                sw.Write(str);
                sw.Flush();
                sw.Close();
                return true;
            }
            catch
            {
                return false;
            }
        }
        #endregion

    }
}
